//
//  LinePreDetailVC.m
//  ImGuider
//
//  Created by llt on 2017/9/13.
//  Copyright © 2017年 AudioCtrip. All rights reserved.
//

#import "LinePreDetailVC.h"
#import "TagView.h"
#import "StarRateView.h"
#import "WPYNavBar.h"
#import "Transition.h"
#import "ProgressBtn.h"

#import "LinePreTab1Cell.h"
#import "LinePreTab2Cell.h"

#import "GuiderDetailVC.h"
#import "UserCommentsVC.h"
#import "UserSubmitQustionVC.h"
#import "IGShare.h"
#import "CityTourPlay.h"
#import "ScenicPlayVC.h"

#import "LinePaymentVC.h"
#import "AllRecordPointVC.h"
#import "ScenicNodePlayVC.h"
@interface LinePreDetailVC () <UITableViewDataSource, UITableViewDelegate, WPYNavBarDelegate, IGAvPlayerManagerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIView *headView;
@property (weak, nonatomic) IBOutlet UIImageView *lineImagaeView;
@property (weak, nonatomic) IBOutlet UILabel *lineNameLabel;
@property (weak, nonatomic) IBOutlet TagView *tagView;
    
    @property (weak, nonatomic) IBOutlet NSLayoutConstraint *tagViewWidth;
    
@property (weak, nonatomic) IBOutlet StarRateView *rateView;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *spotCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *listenMinsLabel;
@property (weak, nonatomic) IBOutlet UILabel *listenCountLabel;

@property (weak, nonatomic) IBOutlet ProgressBtn *playBtn;
@property (weak, nonatomic) IBOutlet UILabel *tryListenLabel;
@property (weak, nonatomic) IBOutlet UIButton *openScenicBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lineImageViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lineImageViewTop;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewBottom;

@property (nonatomic, strong) WPYNavBar *sectionView;

@property (nonatomic, strong) LineModel *lineModel;

@property (nonatomic) BOOL isDrag;

@property (nonatomic, strong) UserSubmitQuestionCell *currentCell;
@property (nonatomic, strong) Question *cquestion;

@property (nonatomic, assign) BOOL isAlways;
@end

@implementation LinePreDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *try = MYLocalizedString(@"PUBLIC_PLAY_TRIALS", nil);
    
    if (try.length > 5) {
        self.tryListenLabel.text = @"";
    } else {
        
        self.tryListenLabel.text = try;
    }
    
    [self.openScenicBtn setTitle:MYLocalizedString(@"CITYTOUR_LISTEN", nil) forState:UIControlStateNormal];
    
    [self rightBarButtonWithImageName:@"分享" selector:@selector(showShareSheet:)];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccessCallback) name:kLoginSuccessNotif object:nil];

    UIView *mengbanView = [UIView new];
    mengbanView.backgroundColor = kMengBanColor;
    [self.lineImagaeView addSubview:mengbanView];
    
    @weakify(self);
    [mengbanView mas_makeConstraints:^(MASConstraintMaker *make) {
        @strongify(self);
        make.edges.equalTo(self.lineImagaeView);
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAudioState:) name:kIGAvPlayerManagerState object:nil];
    
    self.barBGAlpha = 0;
    self.customBarStyle = UIStatusBarStyleLightContent;
    self.playBtn.space = 3.f;
    self.playBtn.progressColor = [UIColor whiteColor];
    self.tagView.tagViewWidth = self.tagViewWidth;
    [self closeAutomaticallyAdjustsScrollViewInsets:self.tableView];
    
    self.tableView.sectionHeaderHeight = 60;
    self.lineImageViewHeight.constant = kScreenWidth * 9.0f / 16;
    self.bottomViewBottom.constant = kBottomHeight;
    
    [ActivityIndicatorView showHUDAddedTo:self.view backgroundColor:kBGColor];
    [self loadDataBlock:nil];
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewDidDisappear:animated];
    
    if ([IGAvPlayerManager shareManeger].isPlay && [IGAvPlayerManager shareManeger].playType == PlayTry && !self.isAlways) {
        [[IGAvPlayerManager shareManeger] stop];
    }
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    self.isAlways = NO;
    [super viewWillAppear:animated];
    
}

- (void)loadDataBlock:(void(^)(void))block {
    
    @weakify(self);
    [NetAPIManager getLineDetailWithLinID:self.lineid block:^(LineModel *model, NSError *error) {
        @strongify(self);
        
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        self.lineModel = model;
        [self setupData];
        if (block) {
            block();
        }
    }];
}

- (void)setupData {
    
    [self.lineImagaeView setImageURL:[NSURL URLWithString:self.lineModel.pictures] placeholderImage:[UIImage imageNamed:@"placeholder_rec"]];
    self.lineNameLabel.text = self.lineModel.linename;
    self.tagView.tagsArray = self.lineModel.tagArray;
    [self.rateView setScore:self.lineModel.score.floatValue / 10.0];
    self.rateView.canRating = NO;
    
    if (self.lineModel.bought && [UserManager sharedManager].user.role != UserRolesTypeAdmin && self.lineModel.pricelevel.integerValue != 0) {
        
        self.priceLabel.text = MYLocalizedString(@"SITEPLAY_PURCHASED", nil);
    } else {
        
        self.priceLabel.text = self.lineModel.price;
    }
    
    self.spotCountLabel.text = self.lineModel.recordcount;
    
    self.listenMinsLabel.text = [NSString stringWithFormat:@"%@mins",self.lineModel.timelabel];
    self.listenCountLabel.text = self.lineModel.visits;
    [self.tableView reloadData];

    if (self.sectionView.LabelArray.count == 3) {
        UILabel *label2 = self.sectionView.LabelArray[1];
        
        label2.text = [NSString localizedStringWithFormat:MYLocalizedString(@"LINEDETAIL_SECTION_COMMENT", nil), self.lineModel.commentnum.intValue];
        
        UILabel *label3 = self.sectionView.LabelArray[2];
        
        label3.text = [NSString localizedStringWithFormat:MYLocalizedString(@"LINEDETAIL_SECTION_QUESTION", nil), self.lineModel.questionnum.intValue];
    }
}

- (WPYNavBar *)sectionView {
    
    if (!_sectionView) {
        _sectionView  = [[WPYNavBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth,60) titleColor:kTitleColor andSelectTitleColor:kThemeColor];
        _sectionView.titleColor = kContentColor;
        _sectionView.titleFont = Font(14);
        _sectionView.delegate = self;
        
        [_sectionView AddNavBarArray:@[MYLocalizedString(@"LINEDETAIL_SECTION_DETAIL", nil),
                                       [NSString localizedStringWithFormat:MYLocalizedString(@"LINEDETAIL_SECTION_COMMENT", nil), self.lineModel.commentnum.intValue],
                                       [NSString localizedStringWithFormat:MYLocalizedString(@"LINEDETAIL_SECTION_QUESTION", nil), self.lineModel.questionnum.intValue]] isBtnLine:YES btnLineColor:kThemeColor];
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(16, 59, kScreenWidth - 32, 1)];
        lineView.backgroundColor = kBGColor;
        [_sectionView addSubview:lineView];
    }
    
    return _sectionView;
}

- (void)showShareSheet:(UIButton *)sender {
    
    [self popSheet];
}

- (void)changeAudioState:(NSNotification *)notif {
    
    NSInteger state = [notif.userInfo[kIGAvPlayerManagerState] integerValue];
    NSString  *url = notif.userInfo[kCurrentPlayURL];
    
    NSNumber * type = notif.userInfo[kPlayType];
    if ((![url isEqualToString:self.cquestion.answer] && ![url isEqualToString:self.lineModel.playpath]) || (type.integerValue != PlayTry && type.integerValue != PlayAnswer)) {
        if (self.playBtn.selected) {
            self.playBtn.selected = NO;
            [self.playBtn setProgress:0.f];
        }
        return;
    }

    switch (state) {
        case AVPlayerPlayStatePause:
        case AVPlayerPlayStateEnd:
        {
            if ([url isEqualToString:self.cquestion.answer]) {
               
                [self.currentCell stopPlay];
                self.cquestion = nil;
                self.currentCell = nil;
                
            } else if([self.lineModel.playpath isEqualToString:[IGAvPlayerManager shareManeger].currentURL]) {

                self.playBtn.selected = NO;
                [self.playBtn setProgress:0.f];
            }
        }
            break;
        case AVPlayerPlayStateBeigin:
        case AVPlayerPlayStatePlaying:
        {
            if([self.lineModel.playpath isEqualToString:[IGAvPlayerManager shareManeger].currentURL]) {
                
                self.playBtn.selected = YES;
            }else{
                self.playBtn.selected = NO;
                [self.playBtn setProgress:0.f];
            }
        }
            break;
    }
    
}


- (IBAction)tryPlay:(UIButton *)sender {

    if (self.cquestion) {
        
        [self.currentCell stopPlay];
        self.cquestion = nil;
        self.currentCell = nil;
        
    }
    
    if (self.playBtn.selected || !self.lineModel) {
        
        [[IGAvPlayerManager shareManeger] pause];
        
        [MobClick event:@"3_0_1"];
        return;
    }
    [MobClick event:@"3_0_2"];
    [IGAvPlayerManager shareManeger].delegate = self;
    
    if (![AppManager sharedManager].allowWhenPlay && [AppManager sharedManager].networkState == AFNetworkReachabilityStatusReachableViaWWAN) {
        
        @weakify(self);
        [IGAlertView alertWithTitle:@"" message:MYLocalizedString(@"PUBLIC_NOWIFI_PLAY_ALERT_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_NOWIFI_PLAY_ALERT_COMMIT", nil) commit:^{
            
            @strongify(self);
            [AppManager sharedManager].allowWhenPlay = YES;
            if (![[IGAvPlayerManager shareManeger].currentURL isEqualToString:self.lineModel.playpath]) {
                [[IGAvPlayerManager shareManeger] playMusic:self.lineModel.playpath withPlayType:PlayTry];
                
            }else{
                [[IGAvPlayerManager shareManeger] play];
            }
            
            //self.playBtn.selected = YES;
            
        } cancel:nil];
        
        return;
    }
    
//    if (![[IGAvPlayerManager shareManeger].currentURL isEqualToString:self.lineModel.playpath]) {
//        [[IGAvPlayerManager shareManeger] playMusic:self.lineModel.playpath withPlayType:PlayTry];
//    }else{
//        [[IGAvPlayerManager shareManeger] play];
//    }
    
    [[IGAvPlayerManager shareManeger] playMusic:self.lineModel.playpath withPlayType:PlayTry];
    //self.playBtn.selected = YES;
}


- (void)updateProgressWith:(CGFloat)value {

    if ([self.lineModel.playpath isEqualToString:[IGAvPlayerManager shareManeger].currentURL] && [IGAvPlayerManager shareManeger].playType == PlayTry) {
        if ([IGAvPlayerManager shareManeger].isPlay) {
             [self.playBtn setProgress:value];
        }
    }

}

- (IBAction)openTheLine:(UIButton *)sender {
    
    if (![IGUtil hasLoginOrPresentLogin]) {
        
        return;
    }
    
    if (!self.lineModel.bought) {
        
        LinePaymentVC * paymentVC = [[LinePaymentVC alloc] init];
        paymentVC.lineModel = self.lineModel;
        paymentVC.delegate = self;
        
        RTRootNavigationController * nav = [[RTRootNavigationController alloc] initWithRootViewController:paymentVC];
        [self presentViewController:nav animated:YES completion:nil];
        
        return;
    }
    
    [self choosePageVCWithAlert:NO];
}



- (void)choosePageVCWithAlert:(BOOL) alert {
    
    
    for (UIViewController *vc in self.navigationController.viewControllers) {
        
        if ([vc isKindOfClass:[BasePlayVC class]]) {
            [self.rt_navigationController removeViewController:vc];
        }
        
        if ([vc isKindOfClass:[LinePreDetailVC class]] && vc != self) {
            [self.rt_navigationController removeViewController:vc];
        }
    }
    
    
    if (self.lineModel.type.integerValue == 1) {
        
        CityTourPlay * vc= [[CityTourPlay alloc] init];
        vc.pageType = 2;
        vc.lineModel = self.lineModel;
        if ([IGAvPlayerManager shareManeger].isPlay) {
            
            [[IGAvPlayerManager shareManeger] pause];
        }
        [self.navigationController pushViewController:vc animated:YES];
        
    } else {
        
        if (self.lineModel.hascode.integerValue > 0) {
            
            ScenicNodePlayVC * vc = [[ScenicNodePlayVC alloc] init];
            vc.alert = NO;
            vc.lineid = self.lineModel.lineid;
            [self.navigationController pushViewController:vc animated:YES];
            
        }else {
            ScenicPlayVC *playVC = [[ScenicPlayVC alloc] init];
            playVC.alert = alert;
            [AppManager sharedManager].lineid = self.lineid;
            playVC.lineModel = self.lineModel;
            
            playVC.pageType = 2;
            //self.NoAnimation = YES;
            [self.navigationController pushViewController:playVC animated:YES];
        }
    }
}


- (void)paySuccessCallback {
    [ActivityIndicatorView showHUDAddedTo:self.view];
    
    @weakify(self);
    [self loadDataBlock:^{
        @strongify(self);
        if (self.lineModel.bought) {
            [self choosePageVCWithAlert:YES];
        }
    }];
}

- (void)loginSuccessCallback {
    [ActivityIndicatorView showHUDAddedTo:self.view];
    [self loadDataBlock:nil];
}


#pragma mark -UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.lineModel ? 3 : 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.row == 0) {
        LinePreTab1Cell *cell1 = [tableView dequeueReusableCellWithIdentifier:@"tab1"];
        cell1.linemodel = self.lineModel;
        cell1.delegate = self;
        cell1.superVC = self;
        return cell1;
    }
    
    LinePreTab2Cell *cell = [tableView dequeueReusableCellWithIdentifier:indexPath.row == 1 ? @"tab2":@"tab3"];
    cell.type = indexPath.row;
    cell.linemodel = self.lineModel;
    cell.delegate = self;
    cell.superVC = self;
    
    return cell;
}

#pragma mark -UITableViewDelegate

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    return self.sectionView;
}

#pragma mark -UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat header = self.headView.frame.size.height - kNavigationBarHeight - 8;//这个header其实是section的header到导航栏的距离
    CGFloat distance = scrollView.contentOffset.y;
    
    self.title = @"";
    
    if (distance <= header && distance >= 0) {
        
        scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        
        self.barBGAlpha = distance / header;
        
    } else if (distance > header) {
        
        scrollView.contentInset = UIEdgeInsetsMake(kNavigationBarHeight, 0, 0, 0);
        
        self.barBGAlpha = 1;
        self.title = self.lineModel.linename;
    } else {
        
        scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        self.barBGAlpha = 0;
        
        self.lineImageViewTop.constant = distance;
        self.lineImageViewHeight.constant = kScreenWidth * 9 / 16 - distance;
    }
    
    if (self.barBGAlpha > 0.5) {
        self.customBarStyle = UIStatusBarStyleDefault;
    } else {
        self.customBarStyle = UIStatusBarStyleLightContent;
    }
    
    if (!self.isDrag) {
        return;
    }
    
    CGRect rect = [self.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    if (distance < (CGRectGetMaxY(rect) - kNavigationBarHeight - 60) - 8) {
        
        self.sectionView.selectIndex = 0;
    } else {
        
        rect = [self.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
        
        if (distance < (CGRectGetMaxY(rect) - kNavigationBarHeight - 60) - 8) {
            
            self.sectionView.selectIndex = 1;
        } else {
            
            self.sectionView.selectIndex = 2;
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    self.isDrag = YES;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    self.isDrag = NO;
}

- (BOOL)scrollViewShouldScrollToTop:(UIScrollView *)scrollView {
    self.isDrag = YES;
    
    [scrollView setContentOffset:CGPointZero animated:YES];
    return NO;
}


#pragma mark -webinterface

- (void)jumpAllPoint{
    
    AllRecordPointVC * vc = [AllRecordPointVC new];
    
    vc.lineModel = self.lineModel;
    self.isAlways = YES;
    [self.navigationController pushViewController:vc animated:YES];

}
- (void)jumpguider {
    
    GuiderDetailVC * vc = [GuiderDetailVC new];
    vc.guiderID = self.lineModel.guideid;
    
    //self.NoAnimation = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)jumpcomment {
    
    UserCommentsVC * commentsVC = [[UserCommentsVC alloc] init];
    commentsVC.lineID = self.lineModel.lineid;
    
    //self.NoAnimation = YES;
    [self.navigationController pushViewController:commentsVC animated:YES];
}

- (void)jumpquestion {
    
    UserSubmitQustionVC * vc = [[UserSubmitQustionVC alloc] init];
    
    vc.lineModel = self.lineModel;
    //self.NoAnimation = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)reloadTab2Height {
    
    [self.tableView reloadData];
}


#pragma mark - UserSubmitQuestionCellDelegate

- (void)answerAudioTapped:(UserSubmitQuestionCell *)cell question:(Question *)question {
    
    if ([question.qid isEqualToString:self.cquestion.qid]) {
        [[IGAvPlayerManager shareManeger] pause];
        return;
    }
    
    if ([[IGAvPlayerManager shareManeger].currentURL isEqualToString:question.answer]) {
        [[IGAvPlayerManager shareManeger] play];
    } else {
        
        if ([[IGAvPlayerManager shareManeger].currentURL isEqualToString:self.cquestion.answer]) {
            [self.currentCell stopPlay];
        }
        
        [[IGAvPlayerManager shareManeger] playMusic:question.answer withPlayType:PlayAnswer];
        
        self.playBtn.selected = NO;
        self.playBtn.progress = 0.f;
    }
    
    [NetAPIManager clickCountWithID:question.qid type:@(3).stringValue];
    self.currentCell = cell;
    self.cquestion = question;
    [cell startPlay];
}

#pragma  mark - WPYNavBarDelegate
-(void)selectChangetoViewNum:(NSInteger)num {
    
    [self.tableView setContentInset:UIEdgeInsetsMake(kNavigationBarHeight, 0, 0, 0)];
    
    NSIndexPath *indexpath = [NSIndexPath indexPathForRow:num inSection:0];
    self.isDrag = NO;
//    
    [self.tableView scrollToRowAtIndexPath:indexpath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

//- (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC {
//    // _navOperation = operation;
//    
//    if (//self.NoAnimation) {
//        
//        return nil;
//    }
//    
//    return [Transition transitionWithTransitionType:operation == UINavigationControllerOperationPush ? PageCoverTransitionPush:PageCoverTransitionPop];
//}

#pragma mark - SnailSheetViewDelegate

- (void)sheetView:(SnailSheetView *)sheetView didSelectItemAtSection:(NSInteger)section index:(NSInteger)index {
    @weakify(self)
    SnailSheetItemModel *model = [self sheetModels][section][index];
    
    NSString * descrbe = self.lineModel.type.integerValue == 1 ? MYLocalizedString(@"SHARE_LINE_MESSAGE", nil):MYLocalizedString(@"SHARE_SCENIC_MESSAGE", nil);
    self.sl_popupController.didDismiss = ^(SnailPopupController * _Nonnull popupController) {
        @strongify(self);
        
        [IGShare shareWebPageToPlatformType:model.platformType withURL:[IGShare getUrlWithPath:[NSString stringWithFormat:@"fxh5customline/%@",self.lineid]] title:self.lineModel.linename descr:descrbe thumImage:self.lineModel.pictures object:self.lineModel.playpath type:2 completion:nil];
    };
    [self.sl_popupController dismiss];
}


@end
